package com.zmx.patients.view.activity;


import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.zmx.patients.BaseActivity;
import com.zmx.patients.R;
import com.zmx.patients.okhttp.OkHttp3ClientManager;
import com.zmx.patients.utils.AllUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * 程序猿：胖胖祥
 * 时 间：2020/10/10  22:51
 * 功 能：舌苔问诊
 */

public class TongueCoatingActivity extends BaseActivity {

    @BindView(R.id.she_head)
    ImageView sheHead;
    @BindView(R.id.button)
    Button button;
    @BindView(R.id.registered)
    Button registered;

    private String image_url;
    private String update_url;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_tongue_coating;
    }

    @Override
    protected void initViews() {

        ButterKnife.bind(this);
        setToolbar(R.id.tool_bar);

    }


    Bitmap bitmap;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {

            if (requestCode == 1) {//可以判断是我们那个Intent发出的请求

                image_url = getTakePhotoPath(data);
                Bundle bundle = data.getExtras();//在相机这个应用中包含的是整个二进制流
                bitmap = (Bitmap) bundle.get("data");
                sheHead.setImageBitmap(bitmap);
                handler.sendEmptyMessage(1);


            }
        }


    }

    /***
     * 获取拍照后的路径
     * @param data
     * @return
     */
    private SimpleDateFormat t = new SimpleDateFormat("yyyyMMddHHmmss");

    public String getTakePhotoPath(Intent data) {

        Log.e("进来了", "进来了");

        Bitmap photo = null;
        Uri uri = data.getData();
        if (uri != null) {
            photo = BitmapFactory.decodeFile(uri.getPath());
        }
        if (photo == null) {
            Bundle bundle = data.getExtras();
            if (bundle != null) {
                photo = (Bitmap) bundle.get("data");
            } else {

                return "";
            }
        }

        FileOutputStream fileOutputStream = null;
        try {
            // 获取 SD 卡根目录
            String saveDir = Environment.getExternalStorageDirectory() + "/fiberstore_photos";
            // 新建目录
            File dir = new File(saveDir);
            if (!dir.exists()) dir.mkdir();
            // 生成文件名

            String filename = "MT" + (t.format(new Date())) + ".jpg";
            /**新建文件*/
            File file = new File(saveDir, filename);
            /***打开文件输出流*/
            fileOutputStream = new FileOutputStream(file);
            // 生成图片文件
            /**
             * 对应Bitmap的compress(Bitmap.CompressFormat format, int quality, OutputStream stream)方法中第一个参数。
             * CompressFormat类是个枚举，有三个取值：JPEG、PNG和WEBP。其中，
             * PNG是无损格式（忽略质量设置），会导致方法中的第二个参数压缩质量失效，
             * JPEG不解释，
             * 而WEBP格式是Google新推出的，据官方资料称“在质量相同的情况下，WEBP格式图像的体积要比JPEG格式图像小40%。
             */
            photo.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
            /***相片的完整路径*/

            Log.e("进来了", "进来了" + file.getPath());
            return file.getPath();
        } catch (Exception e) {
            e.printStackTrace();

            Log.e("进来了", "yiclgal" + e.toString());
        } finally {
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return "";
    }


    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {

                case 1:

                    showLoadingView("正在分析中...");
                    upload(image_url);
                    break;

                case 2:

                    getData();


                    break;
                case 3:

                    String message = msg.obj.toString();
                    Log.e("返回参数", "返回参数" + message);
                    try {

                        if (message.startsWith("\ufeff")) {
                            message = message.substring(1);
                        }


                        JSONObject jsonObject = new JSONObject(message);
                        String data = jsonObject.getString("data");

                        JSONObject object = new JSONObject(data);

                        if (object.getString("message").equals("调用成功")) {

                            handler.postDelayed(new Runnable() {
                                @Override
                                public void run() {

                                    dismissLoadingView();

                                    if (bitmap != null) {

                                        Intent intent = new Intent(mActivity, TongueCoatingResultsActivity.class);
                                        intent.putExtra("bitmap", bitmap);
                                        intent.putExtra("data", data);
                                        startActivity(intent);

                                    }

                                }
                            }, 9000);//3秒后执行Runnable中的run方法


                        } else {

                            dismissLoadingView();
                            Toast(object.getString("message"));

                        }


                    } catch (JSONException e) {
                        e.printStackTrace();
                        Log.e("异常", "异常" + e.toString());
                    }


                    break;

            }

        }
    };


    private void upload(String url) {// selImageList 包含图片路径的list


        Log.e("数据", "url" + url);
        OkHttpClient okHttpClient = new OkHttpClient();

        MultipartBody.Builder builder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM); //表单上传文件


        File file = new File(url); //根据路径创建file对象
        builder.addFormDataPart("image[]", //
                file.getName(),
                RequestBody.create(MediaType.parse("image/jpeg"), file)
        );

        RequestBody requestBody = builder.build();
        Request request = new Request.Builder()
                .url("http://zmx.123xk.cn/admin/api.doctor/AddImg")
                .post(requestBody)
                .build();

        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("onFailure: ", e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                try {

                    JSONObject object = new JSONObject(response.body().string());

                    Log.e("数据", "数据" + object.toString());

                    if (object.getString("code").equals("1")) {

                        JSONObject data = object.getJSONObject("data");
                        JSONArray array = data.getJSONArray("url");
                        for (int i = 0; i < array.length(); i++) {


                            update_url = array.get(i).toString();

                        }
                        handler.sendEmptyMessage(2);

                    } else {
                        Toast(object.getString("msg"));
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });

    }

    /**
     * 获取所有提问
     */
    private String app_id;
    private String timestamp;
    private String sign;

    public void getData() {

        app_id = "7932e84d77254e95b504472eab730ed4";
        timestamp = t.format(new Date());

        StringBuilder requestparams = new StringBuilder();
        requestparams.append(AllUtil.md5(timestamp) + app_id);

        Log.e("签名", "签名" + timestamp);
        sign = AllUtil.md5(requestparams.toString());
        Log.e("签名1", "签名1" + sign);
        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("app_id", "f5f83edbed3a4b42");
        params.put("timestamp", timestamp);
        params.put("version", "1.0");
        params.put("timeout_express", "30"); // 当前时间戳
        params.put("sign", sign);
        params.put("method", "jiuti");
        params.put("imgpath", update_url);
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://www.aibayes.cn/api/analysis", params, handler, 3, 404);

    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.registered, R.id.button})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.registered:

                startActivity(TongueCoatingMessageActivity.class);


                break;
            case R.id.button:

                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(intent, 1);


                break;
        }
    }
}
